package com.diankangwo.controller;

import com.diankangwo.constant.resultMsg;
import com.diankangwo.dao.CommodityDAO;
import com.diankangwo.dao.ShoppingCartDAO;
import com.diankangwo.dao.UserDAO;
import com.diankangwo.domain.Commodity;
import com.diankangwo.domain.ShoppingCart;
import com.diankangwo.domain.UserInfo;
import com.diankangwo.dto.ShoppingCartDTO;
import com.diankangwo.util.EntityDtoConverter;
import com.diankangwo.util.PageSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 购物车控制器
 *
 * @author xiaoyu
 */
@Controller
@Api(description = "购物车")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartDAO shoppingCartDao;
    @Autowired
    private CommodityDAO commodityDAO;
    @Autowired
    private UserDAO userDao;

    /**
     * 获取我的购物车列表
     *
     * @param accessToken
     * @return
     */
    @ApiOperation(value = " 获取我的购物车列表", notes = "")
    @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String")
    @ResponseBody
    @RequestMapping(value = "/shopping_cart", method = RequestMethod.GET)
    public String list(String accessToken, int pageNo, int pageSize) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        PageSupport<ShoppingCart> scList = null;
        List<ShoppingCartDTO> scDTOList = new ArrayList<>();
        if (user != null) {
            scList = shoppingCartDao.findByUserId(user.getId(), pageNo, pageSize);
            if (scList != null) {
                EntityDtoConverter ed = new EntityDtoConverter();
                for (int i = 0; i < scList.getResultData().size(); i++) {
                    ShoppingCartDTO scDto = new ShoppingCartDTO();
                    ShoppingCart sc = scList.getResultData().get(i);
                    try {
                        scDto = (ShoppingCartDTO) ed.entityConvertDto(sc, scDto);
                        scDto.setCommodityPic(commodityDAO.find(scList.getResultData().get(i).getCommodityId()).getCommodityPicLarge());
                        scDTOList.add(scDto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                code = "1";
                msg = "获取成功！";
            } else {
                code = "1";
                msg = "未查询到购物车记录！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, scDTOList);
    }

    /**
     * 添加购物车
     *
     * @param accessToken token
     * @param commodityId 商品ID
     * @param selected    选择
     * @param number      数量
     * @return
     */
    @ApiOperation(value = " 添加购物车", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "commodityId", value = "商品ID", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "selected", value = "选择", required = true, dataType = "String"),
            @ApiImplicitParam(name = "number", value = "数量", required = true, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/shopping_cart", method = RequestMethod.POST)
    public String add(String accessToken, Integer commodityId, String selected, Integer number) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        ShoppingCart sc = new ShoppingCart();
        if (user != null) {
            PageSupport<ShoppingCart> scList = shoppingCartDao.findByUserId(user.getId(), 1, Integer.MAX_VALUE);
//            if (scList != null) {
//                for (int i = 0; i < scList.size(); i++) {
//                    Commodity c = commodityDAO.find(scList.get(i).getCommodityId());
//                    if (scList.get(i).getCommodityId() == commodityId) {
//                        sc = scList.get(i);
//                        sc.setCommodityNumber(scList.get(i).getCommodityNumber() + number);
//                        sc.setSelected(selected);
//                        sc.setCommodityName(c.getCommodityName());
//                        sc.setCommodityPriceShop(c.getCommodityPriceShop());
//                        sc.setSelected(selected);
//                        sc.setCommodityPriceUser(c.getCommodityPriceUser());
//                    } else {
//                    sc.setCommodityName(c.getCommodityName());
//                    sc.setCommodityId(commodityId);
//                    sc.setCommodityNumber(number);
//                    sc.setUserId(user.getId());
//                    sc.setShoppingTime(new Date());
//                    sc.setCommodityPriceShop(c.getCommodityPriceShop());
//                    sc.setSelected(selected);
//                    sc.setCommodityPriceUser(c.getCommodityPriceUser());
////                    }
//                    sc = shoppingCartDao.insert(sc);
//                }
//            } else {
            Commodity c = commodityDAO.find(commodityId);
            sc.setCommodityName(c.getCommodityName());
            sc.setCommodityPriceShop(c.getCommodityPriceShop());
            sc.setCommodityPriceUser(c.getCommodityPriceUser());
            sc.setCommodityPriceVip(c.getCommodityPriceVip());
            sc.setCommodityPic(c.getCommodityPicLarge());
            sc.setCommodityId(commodityId);
            sc.setCommodityNumber(number);
            sc.setUserId(user.getId());
            sc.setShoppingTime(new Date());
            sc.setSelected(selected);
            sc.setFreight(c.getFreight());
            sc = shoppingCartDao.insert(sc);
//            }

            if (sc != null) {
                code = "1";
                msg = "添加成功！";
            } else {
                msg = "系统异常，添加失败！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, sc);
    }

    /**
     * 删除我的购物车数据
     *
     * @param accessToken
     * @param id
     * @return
     */
    @ApiOperation(value = "删除我的购物车数据", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "id", value = "购物车ID", required = true, dataType = "Integer")
    })
    @ResponseBody
    @RequestMapping(value = "/shopping_cart/del", method = RequestMethod.POST)
    public String del(String accessToken, String id) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            try {
                JSONArray json = JSONArray.fromObject(id); // 首先把字符串转成 JSONArray 对象
                List l = JSONArray.toList(json);
                for (Object object : l) {
                    ShoppingCart sc = shoppingCartDao.find((int) object);
                    if (sc.getStatus() == 0) {
                        shoppingCartDao.delete(shoppingCartDao.find((int) object));
                        code = "1";
                        msg = "删除成功！";
                    } else {
                        code = "2";
                        msg += sc.getCommodityName() + "删除失败！未查询到购物车信息！";
                    }
                }
            } catch (Exception e) {
                code = "1";
                msg = "删除异常!";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, null);
    }

    /**
     * 修改我的购物车列表信息
     *
     * @param accessToken
     * @param data
     * @return
     */
    @ApiOperation(value = "修改我的购物车列表信息", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "accessToken", value = "token", required = true, dataType = "String"),
            @ApiImplicitParam(name = "data", value = "数据列表", required = true, dataType = "String")
    })
    @ResponseBody
    @RequestMapping(value = "/shopping_cart/update", method = RequestMethod.POST)
    public String update(String accessToken, String data) {
        UserInfo user = userDao.getUserByToken(accessToken);
        String code = "2";
        String msg = "处理异常！";
        if (user != null) {
            try {
                JSONArray json = JSONArray.fromObject(data); // 首先把字符串转成 JSONArray  对象
                if (json.size() > 0) {
                    for (int i = 0; i < json.size(); i++) {
                        JSONObject job = json.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                        ShoppingCart sc = shoppingCartDao.find(Integer.parseInt(job.get("id").toString()));
                        if (sc.getStatus() == 0) {
                            sc.setCommodityNumber(Integer.parseInt(job.get("number").toString()));
                            shoppingCartDao.saveOrUpdate(sc);
                            code = "1";
                            msg = "更新成功！";
                        } else {
                            code = "2";
                            msg += sc.getCommodityName() + "修改失败！未查询到购物车信息！";
                        }
                    }
                }
            } catch (Exception e) {
                msg = "系统异常，更新失败！";
            }
        } else {
            msg = "未查询到用户信息！";
        }
        return resultMsg.mapToJson(code, msg, null);
    }
}
